
const { ccclass, property } = cc._decorator;

@ccclass('BuriedPoint')
export class BuriedPoint extends cc.Component {
    // ========== 配置参数 ==========
    // private  API_URL: string = "https://81.70.255.4:443/ecpm/maiDian/callback";//测试环境URL
    private readonly API_URL: string = "www.ggx.net/ecpm/ecpm/maiDian/callback";// 正式环境URL
    private  APP_ID: string = "your_appid";    // 替换为实际应用ID-------自己填写
    private  CODE: string = "login_code";      // 登录后获取的code-------登录获取
    private  ANONYMOUS_CODE: string = "temp_code"; // 临时anonymousCode

    private  COUNTRY: string = "CN"//用户所在的国家-------自己填写
    private  MODELX: string =  ""//设备型号-------登录获取
    private  GENDER: string = "0"//用户性别//-------登录获取
    private  AVATARUrl: string = ""//用户头像的 URL 地址-------登录获取
    private  APPNAME: string = ""//应用名称-------自己填写
    private  CITYX: string = ""//城市的详细信息-------自己填写
    private  VERSION: string = "6.6.3"//应用版本号-------自己填写
    private  PLATFORM: string = "devtools"//平台标识-------登录获取
    private  SYSTEM: string = cc.sys.os//系统版本或其他系统信息，如操作系统版本-------登录获取
    private  PROVINCE: string = ""//用户所在的省份-------自己填写
    private  BRAND: string = "iPhone"//设备品牌------登录获取
    private  SDKVERSION: string = "3.55.0"//SDK 版本------自己填写
    private  USERINFO: string = ""//用户信息------登录获取

    private  INTERVAL_DAYS: number = 30;       // 发送间隔天数

    // ========== 核心逻辑 ==========
    public sendBuriedRequest() {

        if(window["tt"]){
            let tt=window["tt"];
            let self=this;
            tt.login({
             success(res) {
                self.CODE = res.code;
                 // 获取用户信息
                 tt.getUserInfo({
                     success(infoRes) {
                         self.USERINFO = JSON.stringify(infoRes.userInfo);
                         self.AVATARUrl = infoRes.userInfo.avatarUrl;
                         self.GENDER = infoRes.userInfo.gender.toString();
     
                         // 获取系统信息
                         const systemInfo = tt.getSystemInfoSync();
                         self.SYSTEM = systemInfo.system;
                         self.BRAND = systemInfo.brand;
                         self.MODELX = systemInfo.model;
                         console.error("获取用户信息成功", systemInfo);
     
                         self.sendRequest();
                     },
                     fail(err) {
                         console.error("获取用户信息失败", err);
                         self.sendRequest();
                     }
                 });
             },
             fail(err) {
                 console.error("登录失败", err);
                 self.sendRequest();
             }
         });
         }
    }

    sendRequest(){
        if (!this.checkSendInterval()) {
            console.warn("[埋点] 未达到发送间隔要求");
            return;
        }
        const requestData = this.buildRequestData();
        this.executePostRequest(requestData);
    }

    // 构建请求数据（包含系统信息）
    private buildRequestData(): object {
        return {
            appid: this.APP_ID,
            code: this.CODE,
            anonymousCode: this.ANONYMOUS_CODE,

            country: this.COUNTRY,
            modelx: this.MODELX,
            gender:this.GENDER,
            avatarUrl: this.AVATARUrl,
            appName: this.APPNAME,
            cityx: this.CITYX,
            version: this.VERSION,
            system: this.SYSTEM,
            province: this.PROVINCE,
            brand: this.BRAND,
            SDKVersion: this.SDKVERSION,
            userinfo:this.USERINFO,

            platform: cc.sys.platform,     // 自动获取平台‌:ml-citation{ref="2,8" data="citationList"}
            os: cc.sys.os,                // 自动获取操作系统‌:ml-citation{ref="2,8" data="citationList"}
            timestamp: Date.now()
        };
    }

    // 执行POST请求（XMLHttpRequest实现）
    private executePostRequest(data: object) {
        console.log("[埋点]");
        const xhr = new XMLHttpRequest();
        xhr.open("POST", this.API_URL, true);
        xhr.setRequestHeader("Content-Type", "application/json");

        // 改为表单格式的请求头
        // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    console.log("[埋点成功]", xhr.responseText);
                    this.recordSendTime(); // 记录成功时间‌:ml-citation{ref="8" data="citationList"}
                } else {
                    console.error("[埋点失败]", xhr.status, xhr.statusText);
                }
            }
        };

        // 将对象转换为表单格式字符串
        // const formData = this.objectToFormData(data);
        // xhr.send(formData);
        xhr.send(JSON.stringify(data));
    }

    // 新增数据格式转换方法
    private objectToFormData(data: object): string {
        return Object.entries(data)
            .map(([key, value]) =>
                `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
            )
            .join("&");
    }

    // ========== 频率控制 ==========
    private checkSendInterval(): boolean {
        const lastTime = parseInt(cc.sys.localStorage.getItem("lastBuriedTime") || "0");
        return Date.now() - lastTime > this.INTERVAL_DAYS * 86400000;
    }

    private recordSendTime() {
        cc.sys.localStorage.setItem("lastBuriedTime", Date.now().toString());
    }
}
